import { Component } from "react";
import { withRouter } from "react-router-dom";
import { Menu } from "antd";
import { setStorage, getStorage } from "../../utils";
import menuList from "../../router/index";

class leftNav extends Component<any> {
  componentDidMount(): void {
    const pathname = this.props.location.pathname;
    this.props.setBreadcrumb(pathname);
  }

  // 菜单选择
  onSelected = ({ keyPath, key }: { keyPath: Array<string>; key: string }) => {
    // console.log("keyPath:", keyPath);
    // console.log("key:", key);
    // 选中项的具体位置，可以用来查找展开的菜单
    setStorage("keyPath", keyPath);
    // @ts-ignore
    this.props.history.push(key);
    this.props.setBreadcrumb(key);
  };

  // 菜单默认选中
  defaultSelectedKeys = () => {
    // @ts-ignore
    return [this.props.location.pathname];
  };
  // 菜单默认展开
  defaultOpenKeys = () => {
    let defaultOpenKeysArr: Array<string> | null = getStorage("keyPath");
    if (!defaultOpenKeysArr) {
      return [];
    }
    defaultOpenKeysArr.shift();
    return defaultOpenKeysArr;
  };

  render() {
    return (
      <Menu
        mode="inline"
        theme="dark"
        items={menuList}
        defaultOpenKeys={this.defaultOpenKeys()}
        selectedKeys={this.defaultSelectedKeys()}
        onSelect={this.onSelected}
      />
    );
  }
}

export default withRouter(leftNav);
